package com.retoc.oawx.controller;

import com.retoc.oawx.common.util.R;
import com.retoc.oawx.config.shiro.JWTUtil;
import com.retoc.oawx.domain.req.PageReq;
import com.retoc.oawx.domain.req.MessageReq;
import com.retoc.oawx.service.MessageService;
import com.retoc.oawx.task.MessageTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/message")
@Api("消息模块网络接口")
public class MessageController {
    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageTask messageTask;

    @PostMapping("/searchMessageByPage")
    @ApiOperation("获取用户消息分页信息列表")
    public R searchMessageByPage(@Valid @RequestBody PageReq req, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        int start = (req.getPage() - 1) * req.getLength();
        List<HashMap> list = messageService.searchMessageByPage(userId, start, req.getLength());
        return R.ok().put("result", list);
    }

    @PostMapping("searchMessageById")
    @ApiOperation("根据ID查询消息")
    public R searchMessageById(@Valid @RequestBody MessageReq req) {
        HashMap map = messageService.searchMessageById(req.getId());
        return R.ok().put("result", map);
    }

    @PostMapping("updateUnreadMessage")
    @ApiOperation("更新未读消息变成已读消息")
    public R updateUnreadMessage(@Valid @RequestBody MessageReq req) {
        long rows = messageService.updateUnreadMessage(req.getId());
        return R.ok().put("result", rows >= 1);
    }

    @PostMapping("deleteMessageRefById")
    @ApiOperation("删除消息")
    public R deleteMessageRefById(@Valid @RequestBody MessageReq req) {
        long rows = messageService.deleteMessageRefById(req.getId());
        return R.ok().put("result", rows >= 1);
    }

    @GetMapping("/refreshMessage")
    @ApiOperation("刷新用户信息")
    public R refreshMessage(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        messageTask.receivedAsync(userId + "");
        long lastRow = messageService.searchLastCount(userId);
        long unreadCount = messageService.searchUnreadCount(userId);
        return R.ok().put("lastRows",lastRow).put("unreadRows",unreadCount);
    }
}
